const Router = require('koa-router')
const { ChatHistory, sequelize } = require('../models')
const auth = require('../middleware/auth')

const router = new Router({ prefix: '/api/chat' })

// 获取对话历史
router.get('/history', auth.checkPermission('chat:read'), async (ctx) => {
  try {
    const { session_id, limit = 20, offset = 0 } = ctx.query
    const user_id = ctx.state.user.userId

    const where = { user_id }
    if (session_id) {
      where.session_id = session_id
    }

    const histories = await ChatHistory.findAll({
      where,
      order: [['created_at', 'DESC']], // 改为DESC获取最新的记录
      limit: parseInt(limit),
      offset: parseInt(offset)
    })

    // 转换数据格式，使其与前端期望的格式匹配
    const formattedHistories = histories.map(history => ({
      id: history.id,
      role: history.role,
      content: history.message, // message -> content
      timestamp: history.created_at,
      session_id: history.session_id,
      messageType: history.metadata?.messageType || 'text',
      data: history.metadata?.data || null,
      token_usage: history.token_usage
    }))

    ctx.body = {
      success: true,
      data: formattedHistories,
      message: '获取对话历史成功'
    }
  } catch (error) {
    console.error('获取对话历史失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取对话历史失败',
      error: error.message
    }
  }
})

// 保存用户消息
router.post('/messages', auth.checkPermission('chat:write'), async (ctx) => {
  try {
    const { message, role, session_id, metadata } = ctx.request.body
    const user_id = ctx.state.user.userId

    const chatMessage = await ChatHistory.create({
      user_id,
      message,
      role,
      session_id,
      metadata
    })

    ctx.body = {
      success: true,
      data: chatMessage,
      message: '消息保存成功'
    }
  } catch (error) {
    console.error('保存消息失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '保存消息失败',
      error: error.message
    }
  }
})

// 获取用户的聊天会话列表
router.get('/sessions', auth.checkPermission('chat:read'), async (ctx) => {
  try {
    const user_id = ctx.state.user.userId

    // 查询用户的所有会话，按最后更新时间排序
    const sessions = await ChatHistory.findAll({
      where: { user_id },
      attributes: [
        'session_id',
        [sequelize.fn('MIN', sequelize.col('created_at')), 'created_at'],
        [sequelize.fn('MAX', sequelize.col('updated_at')), 'updated_at'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'message_count'],
        [sequelize.fn('SUM', sequelize.col('token_usage')), 'token_usage']
      ],
      group: ['session_id'],
      order: [[sequelize.fn('MAX', sequelize.col('updated_at')), 'DESC']],
      raw: true
    })

    // 格式化会话数据并生成标题
    const formattedSessions = sessions.map(session => {
      // 生成会话标题 - 获取第一条用户消息作为标题
      const title = `会话 ${session.session_id?.slice(-8) || 'Unknown'}`
      
      return {
        id: session.session_id,
        title: title,
        created_at: session.created_at,
        updated_at: session.updated_at,
        message_count: parseInt(session.message_count) || 0,
        token_usage: parseInt(session.token_usage) || 0
      }
    })

    // 为每个会话获取第一条用户消息作为真实标题
    for (const session of formattedSessions) {
      const firstMessage = await ChatHistory.findOne({
        where: { 
          user_id,
          session_id: session.id,
          role: 'user' 
        },
        order: [['created_at', 'ASC']],
        attributes: ['message']
      })
      
      if (firstMessage && firstMessage.message) {
        // 截取前30个字符作为标题
        session.title = firstMessage.message.length > 30 
          ? firstMessage.message.substring(0, 30) + '...'
          : firstMessage.message
      }
    }

    ctx.body = {
      success: true,
      data: formattedSessions,
      message: '获取会话列表成功'
    }
  } catch (error) {
    console.error('获取会话列表失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取会话列表失败',
      error: error.message
    }
  }
})

// 创建新会话
router.post('/sessions', auth.checkPermission('chat:write'), async (ctx) => {
  try {
    const { title } = ctx.request.body
    const user_id = ctx.state.user.userId
    
    // 生成新的会话ID
    const session_id = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    ctx.body = {
      success: true,
      data: {
        id: session_id,
        title: title || '新对话',
        created_at: new Date(),
        updated_at: new Date(),
        message_count: 0,
        token_usage: 0
      },
      message: '创建会话成功'
    }
  } catch (error) {
    console.error('创建会话失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '创建会话失败',
      error: error.message
    }
  }
})

// 删除会话
router.delete('/sessions/:sessionId', auth.checkPermission('chat:delete'), async (ctx) => {
  try {
    const { sessionId } = ctx.params
    const user_id = ctx.state.user.userId

    // 删除该会话的所有消息
    await ChatHistory.destroy({ 
      where: { 
        user_id,
        session_id: sessionId
      }
    })

    ctx.body = {
      success: true,
      message: '删除会话成功'
    }
  } catch (error) {
    console.error('删除会话失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '删除会话失败',
      error: error.message
    }
  }
})

// 清除对话历史
router.delete('/history', auth.checkPermission('chat:delete'), async (ctx) => {
  try {
    const { session_id } = ctx.query
    const user_id = ctx.state.user.userId

    const where = { user_id }
    if (session_id) {
      where.session_id = session_id
    }

    await ChatHistory.destroy({ where })

    ctx.body = {
      success: true,
      message: '对话历史清除成功'
    }
  } catch (error) {
    console.error('清除对话历史失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '清除对话历史失败',
      error: error.message
    }
  }
})

module.exports = router